package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.BompPublicQueryService;
import cc.rengu.igas.bomp.facade.bean.*;
import cc.rengu.igas.bomp.facade.enums.BompAuditFlagEnum;
import cc.rengu.igas.bomp.facade.request.*;
import cc.rengu.igas.bomp.facade.response.*;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.BompQueryTypeEnum;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.bean.CompareDataBean;
import cc.rengu.redp.bizimpl.igas.vo.PTxnAuthMap;
import cc.rengu.redp.bizimpl.igas.vo.PTxnGroup;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.UpmpBMchntProdInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntProdInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntProdInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.MchntBaseProdManagerVO;
import cc.rengu.redp.bizimpl.upmp.vo.MchntProdManagerVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-22
 */
@Service
public class UpmpBMchntProdInfoServiceImpl extends ServiceImpl<UpmpBMchntProdInfoMapper, UpmpBMchntProdInfo> implements IUpmpBMchntProdInfoService {
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    private String oprMenuId = "20000030";
    private String oprMenuName = "商户管理:统一支付平台商户管理";
    private String oprBtnNamePrefix = "统一支付平台商户管理";
    private String webNextUrl = "admin/mcmp/bMchntBaseInfo/edit-tabs";

    /**
     * 商户产品信息审核及保存
     * @param instId
     * @param req
     * @param bompMchntManageService
     * @param authPrivilegeCheckService
     * @param traceNo
     * @param optFlag
     * @param manageOprType  对应接口中操作类型字段
     * @return
     * @throws RedpException
     */
    @Override
    public OperationResult mchntProdSave(String instId, MchntProdInfoManageRequest req, BompMchntManageService bompMchntManageService,
                                         IUpmpPrivilegeCheckService authPrivilegeCheckService, String traceNo, String optFlag, String manageOprType) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        /**商户写死必须审核*/
        req.setHeader(CommonUtils.packageBompHeader(traceNo,BompTxnNumEnum.mchntProdInfoManage.getType(),instId,null));

        req.setOprType(manageOprType);
        //商户业务产品的新增、修改都是直接提交审批操作
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)){
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(),
                    oprBtnNamePrefix+BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT+PageOptFlagEnum.OPT_FLAG_ADD.getDesc());
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                req.setChecked(BompAuditFlagEnum.CHECK.getType());
                req.setOprMenuId(oprMenuId);
                req.setOprMenuName(oprMenuName);
                req.setWebNextUrl(webNextUrl);
                //设置主记录是否需要显示
                req.setMasterShowFlag(IgasYesOrNoEnum.No.getType());

            }else {
                /*req.setChecked(BompAuditFlagEnum.NO_CHECK.getType());
                //设置主记录是否需要显示
                req.setMasterShowFlag(IgasYesOrNoEnum.No.getType());*/
                req.setChecked(BompAuditFlagEnum.CHECK.getType());
                req.setOprMenuId(oprMenuId);
                req.setOprMenuName(oprMenuName);
                req.setWebNextUrl(webNextUrl);
                //设置主记录是否需要显示
                req.setMasterShowFlag(IgasYesOrNoEnum.No.getType());
            }
        }else if(PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)){

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(),
                    oprBtnNamePrefix+BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT+PageOptFlagEnum.OPT_FLAG_UPDATE.getDesc());

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                req.setChecked(BompAuditFlagEnum.CHECK.getType());
                req.setOprMenuId(oprMenuId);
                req.setOprMenuName(oprMenuName);
                req.setWebNextUrl(webNextUrl);
                //设置主记录是否需要显示
                req.setMasterShowFlag(IgasYesOrNoEnum.No.getType());

            }else {
                    /*req.setChecked(BompAuditFlagEnum.NO_CHECK.getType());
                    //设置主记录是否需要显示
                    req.setMasterShowFlag(IgasYesOrNoEnum.No.getType());*/
                req.setChecked(BompAuditFlagEnum.CHECK.getType());
                req.setOprMenuId(oprMenuId);
                req.setOprMenuName(oprMenuName);
                req.setWebNextUrl(webNextUrl);
                //设置主记录是否需要显示
                req.setMasterShowFlag(IgasYesOrNoEnum.No.getType());
            }
        }else if(PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(optFlag)||PageOptFlagEnum.OPT_FLAG_REJECT.getType().equals(optFlag)){
            if(PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(optFlag)){
                req.setCheckStatus(PageOptFlagEnum.OPT_FLAG_PASS.getBompCheckStatus());
            }else {
                req.setCheckStatus(PageOptFlagEnum.OPT_FLAG_REJECT.getBompCheckStatus());
            }
            req.setChecked(BompAuditFlagEnum.NO_CHECK.getType());
        }else {
            throw new RedpException("不支持的操作");
        }


        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        try{

            log.trace("商户编号为：" + req.getMchntNo() + "的商户，"+BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<MchntProdInfoManageResponse> response= bompMchntManageService.mchntProdInfoManage(req);

            log.trace("商户编号为：" + req.getMchntNo() + "的商户，"+BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                MchntProdInfoManageResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    result.put("respCode", resp.getRespCode());
                    result.put("respMsg", resp.getRespDesc());
                    log.trace("商户编号为：" + req.getMchntNo() + "的商户，"+BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易成功");
                    return OperationResult.buildSuccessResult(BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易成功",result);
                }else {
                    if(resp.getRespCode().equals("ER12BM48")||resp.getRespCode().equals("ER12BM58")){
                        result.put("respCode", resp.getRespCode());
                        result.put("respMsg", resp.getRespDesc());
                        log.error("商户编号为：" + req.getMchntNo() + "的商户，"+BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易失败");
                        return OperationResult.buildSuccessResult("商户审批通过",result);
                    }else{
                        result.put("respCode", resp.getRespCode());
                        result.put("respMsg", resp.getRespDesc());
                        return OperationResult.buildFailureResult(BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易失败",result);
                    }
                }
            }else{
                result.put("resCode", BusinessContainer.ERROR);
                result.put("resMsg", BompTxnNumEnum.mchntProdInfoManage.getDesc()+"没有获得返回报文");
                log.error("商户编号为：" + req.getMchntNo() + "的商户，"+BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易没有获得返回信息");
                return OperationResult.buildFailureResult(BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易失败",result);
            }
        }catch (Exception e) {
            // TODO: handle exception
            result.put("resCode", BusinessContainer.ERROR);
            result.put("resMsg", e.getMessage());
            log.error("商户编号为：" + req.getMchntNo() + "的商户，"+BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            return OperationResult.buildFailureResult(BompTxnNumEnum.mchntProdInfoManage.getDesc()+"交易失败",result);
        }
    }
    /**
     * 查询获取标准产品列表
     * @param user
     * @param bompQueryService
     * @param traceNo
     * @return
     * @throws RedpException
     */
    @Override
    public List<ProdInfoBean> getProdInfoList(String instId, UpmpUserInfoVO user, BompPublicQueryService bompQueryService, String traceNo) throws RedpException {
        ProdInfoListQueryRequest req = new ProdInfoListQueryRequest();

        req.setHeader(CommonUtils.packageBompHeader(traceNo,BompTxnNumEnum.prodInfoListQurey.getType(),instId,null));
        req.setUserId(user.getId());
        req.setPageIndex(BusinessContainer.PAGEINDEX_FOR_ALL);
        req.setPageSize(BusinessContainer.PAGESIZE_FOR_ALL);

        try{

            log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<ProdInfoListQueryResponse> response= bompQueryService.prodInfoListQuery(req);



            log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                ProdInfoListQueryResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易成功");
                    return resp.getProdInfoList();
                }else {
                    log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易失败");
                    return null;
                }
            }else{
                log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e) {
            // TODO: handle exception
            log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoListQurey.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
    }
    /**
     * 查询获取标准产品信息
     * @param instId
     * @param bompQueryService
     * @param traceNo
     * @return
     * @throws RedpException
     */
    @Override
    public ProdInfoQueryResponse getProdInfo(String instId, BompPublicQueryService bompQueryService, String traceNo, ProdInfoQueryRequest req) throws RedpException {

        req.setHeader(CommonUtils.packageBompHeader(traceNo,BompTxnNumEnum.prodInfoQuery.getType(),instId,null));

        try{

            log.trace("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<ProdInfoQueryResponse> response= bompQueryService.prodInfoQuery(req);
            log.trace("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                ProdInfoQueryResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    log.trace("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易成功");
                    return resp;
                }else {
                    log.error("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易失败");
                    return null;
                }
            }else{
                log.error("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e) {
            // TODO: handle exception
            log.error("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.prodInfoQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
    }

    /**
     * 查询获取基础产品列表
     * @param user
     * @param bompQueryService
     * @param traceNo
     * @return
     * @throws RedpException
     */
    @Override
    public List<BaseProdInfoBean> getBaseProdInfoList(String instId, UpmpUserInfoVO user, BompPublicQueryService bompQueryService, String traceNo) throws RedpException {
        BaseProdInfoListQueryRequest req = new BaseProdInfoListQueryRequest();

        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.baseProdInfoListQuery.getType(),instId,null));
        req.setUserId(user.getId());

        try{

            log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<BaseProdInfoListQueryResponse> response= bompQueryService.baseProdInfoListQuery(req);

            log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                BaseProdInfoListQueryResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易成功");
                    return resp.getBaseProdInfoList();
                }else {
                    log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易失败");
                    return null;
                }
            }else{
                log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e) {
            // TODO: handle exception
            log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.baseProdInfoListQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
    }
    /**
     * 查询获取商户产品列表
     * @param user
     * @param bompQueryService
     * @param traceNo
     * @return
     * @throws RedpException
     */
    @Override
    public List<MchntProdInfoBean> getMchntProdInfoList(String instId, UpmpUserInfoVO user, BompMchntQueryService bompQueryService, String traceNo, String mchntNo, BompQueryTypeEnum queryType) throws RedpException {
        MchntProdListQueryRequest req = new MchntProdListQueryRequest();

        req.setHeader(CommonUtils.packageBompHeader(traceNo,BompTxnNumEnum.mchntProdListQuery.getType(),instId,queryType.getType()));
        req.setUserId(user.getId());
        req.setMchntNo(mchntNo);

        try{

           log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<MchntProdListQueryResponse> response= bompQueryService.mchntProdListQuery(req);

           log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                MchntProdListQueryResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                   log.trace("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易成功");
                    return resp.getMchntProdInfoList();
                }else {
                    log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易失败");
                    return null;
                }
            }else{
                log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e) {
            // TODO: handle exception
            log.error("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("法人行["+user.getInstId()+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdListQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
    }

    /**
     * 查询获取商户产品
     * @param instId
     * @param bompQueryService
     * @param traceNo
     * @return
     * @throws RedpException
     */
    @Override
    public MchntProdInfoQueryResponse getMchntProdInfoDtl(String instId, BompMchntQueryService bompQueryService, String traceNo, MchntProdInfoQueryRequest req,BompQueryTypeEnum queryType) throws RedpException {

        req.setHeader(CommonUtils.packageBompHeader(traceNo,BompTxnNumEnum.mchntProdInfoQuery.getType(),instId,queryType.getType()));

        try{

           log.trace("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<MchntProdInfoQueryResponse> response= bompQueryService.mchntProdInfoQuery(req);

           log.trace("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                MchntProdInfoQueryResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                   log.trace("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易成功");
                    return resp;
                }else {
                    log.error("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易失败");
                    return null;
                }
            }else{
                log.error("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e) {
            // TODO: handle exception
            log.error("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("法人行["+instId+"]用户标识为：" + req.getUserId() + "的用户，"+BompTxnNumEnum.mchntProdInfoQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
    }
    /**
     * 待审核时通过比较待审核临时数据、正式数据明细的id，分别得到得到新增、修改、删除的明细数据集合
     * @param tmps  待审核数据
     * @param formals  正式数据
     * @return
     */
    @Override
    public CompareDataBean getProdCompareFileById(List<MchntProdInfoBean> tmps, List<MchntProdInfoBean> formals) throws RedpException {
        Map<String,MchntProdInfoBean> updCompare = Maps.newHashMap();
        Map<String,MchntProdInfoBean> addCompare = Maps.newHashMap();
        Map<String,MchntProdInfoBean> delCompare = Maps.newHashMap();
        for(MchntProdInfoBean tmp :tmps){
            boolean match = false;
            label1:for(MchntProdInfoBean formal :formals){
                if(tmp.getId().equals(formal.getId())){
                    match=true;
                    List<LabelValueBean> compare = CommonUtils.compareData(tmp,formal,MchntProdInfoBean.class);
                    if(CollectionUtils.isNotEmpty(compare)){
                        updCompare.put(tmp.getId(),tmp);
                    }
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                addCompare.put(tmp.getId(),tmp);
            }
        }
        for(MchntProdInfoBean formal :formals){
            boolean match = false;

            label1:for(MchntProdInfoBean tmp :tmps){
                if(tmp.getId().equals(formal.getId())){
                    match=true;
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                delCompare.put(formal.getId(),formal);
            }
        }
        //jdk8流处理正式表中有，临时表中无的数据，则是需要删除的数据
/*        List<T> delList = formals.stream().filter(a->!tmps.stream().map(b->b.getId()).collect(Collectors.toList()).contains(a.getId())).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(delList)){
            delList.stream().forEach(item->{
                List<LabelValueBean> compare = CommonUtils.compareData(null,item,clazz);
                if(CollectionUtils.isNotEmpty(compare)){
                    delCompare.put(item.getId(),compare);
                }
            });
        }*/

        if(!addCompare.isEmpty()||!updCompare.isEmpty()||!delCompare.isEmpty()){
            return new CompareDataBean(addCompare,updCompare,delCompare);
        }else{
            return null;
        }
    }

    /**
     * 待审核时通过比较待审核临时数据、正式数据明细的id，分别得到得到新增、修改、删除的明细数据集合
     * @param tmps  待审核数据
     * @param formals  正式数据
     * @return
     */
    @Override
    public CompareDataBean getAuthCompareFileById(List<MchntAuthCtrlInfoBean> tmps, List<MchntAuthCtrlInfoBean> formals) throws RedpException {

        //Map<交易大类编码,Map<交易码,MchntAuthCtrlInfoBean>>
        Map<String,Map<String,MchntAuthCtrlInfoBean>> addCompare = Maps.newHashMap();
        Map<String,Map<String,MchntAuthCtrlInfoBean>> updCompare = Maps.newHashMap();
        Map<String,Map<String,MchntAuthCtrlInfoBean>> delCompare = Maps.newHashMap();
        for(MchntAuthCtrlInfoBean tmp :tmps){
            boolean match = false;
            label1:for(MchntAuthCtrlInfoBean formal :formals){
                if(tmp.getId().equals(formal.getId())){
                    match=true;
                    List<LabelValueBean> compare = CommonUtils.compareData(tmp,formal,MchntAuthCtrlInfoBean.class);
                    if(CollectionUtils.isNotEmpty(compare)){
                        Map<String,MchntAuthCtrlInfoBean> txn = updCompare.get(formal.getTxnGroup());
                        if(txn==null){
                            txn = Maps.newHashMap();
                        }
                        txn.put(tmp.getId(),formal);
                        updCompare.put(formal.getTxnGroup(),txn);

                    }
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                Map<String,MchntAuthCtrlInfoBean> txn = addCompare.get(tmp.getTxnGroup());
                if(txn==null){
                    txn = Maps.newHashMap();
                }
                txn.put(tmp.getId(),tmp);
                addCompare.put(tmp.getTxnGroup(),txn);

            }
        }
        for(MchntAuthCtrlInfoBean formal :formals){
            boolean match = false;

            label1:for(MchntAuthCtrlInfoBean tmp :tmps){
                if(tmp.getId().equals(formal.getId())){
                    match=true;
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                Map<String,MchntAuthCtrlInfoBean> txn = delCompare.get(formal.getTxnGroup());
                if(Common.isBlank(txn)){
                    txn = Maps.newHashMap();
                }

                txn.put(formal.getId(),formal);
                delCompare.put(formal.getTxnGroup(),txn);
            }
        }

        if(!addCompare.isEmpty()||!updCompare.isEmpty()||!delCompare.isEmpty()){
            return new CompareDataBean(addCompare,updCompare,delCompare);
        }else{
            return null;
        }
    }

    /**
     * 待审核时通过比较待审核临时数据、正式数据明细的id，分别得到得到新增、修改、删除的明细数据集合
     * @param tmps  待审核数据
     * @param formals  正式数据
     * @return
     */
    @Override
    public CompareDataBean getStageCompareFileById(List<MchntStageInfoBean> tmps, List<MchntStageInfoBean> formals) throws RedpException {
        Map<String,List<LabelValueBean>> updCompare = Maps.newHashMap();
        Map<String,List<LabelValueBean>> addCompare = Maps.newHashMap();
        Map<String,List<LabelValueBean>> delCompare = Maps.newHashMap();
        for(MchntStageInfoBean tmp :tmps){
            boolean match = false;
            label1:for(MchntStageInfoBean formal :formals){
                if(tmp.getId().equals(formal.getId())){
                    match=true;
                    List<LabelValueBean> compare = CommonUtils.compareData(tmp,formal,MchntStageInfoBean.class);
                    if(CollectionUtils.isNotEmpty(compare)){
                        updCompare.put(tmp.getId(),compare);
                    }
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                List<LabelValueBean> compare = CommonUtils.compareData(tmp,null,MchntStageInfoBean.class);
                addCompare.put(tmp.getId(),compare);
            }
        }
        for(MchntStageInfoBean formal :formals){
            boolean match = false;

            label1:for(MchntStageInfoBean tmp :tmps){
                if(tmp.getId().equals(formal.getId())){
                    match=true;
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                List<LabelValueBean> compare = CommonUtils.compareData(null,formal,MchntStageInfoBean.class);
                delCompare.put(formal.getId(),compare);
            }
        }

        if(!addCompare.isEmpty()||!updCompare.isEmpty()||!delCompare.isEmpty()){
            return new CompareDataBean(addCompare,updCompare,delCompare);
        }else{
            return null;
        }
    }

    /**
     * 待审核时通过比较待审核临时数据、正式数据明细的id，分别得到得到新增、修改、删除的明细数据集合
     * @param tmps  待审核数据
     * @param formals  正式数据
     * @return
     */
    @Override
    public CompareDataBean getTxnGroupCompareFileById(List<PTxnGroup> tmps, List<PTxnGroup> formals) throws RedpException {
        Map<String,PTxnGroup> updCompare = Maps.newHashMap();
        Map<String,PTxnGroup> addCompare = Maps.newHashMap();
        Map<String,PTxnGroup> delCompare = Maps.newHashMap();
        for(PTxnGroup tmp :tmps){
            boolean match = false;
            label1:for(PTxnGroup formal :formals){
                if(tmp.getTxnGroup().equals(formal.getTxnGroup())){
                    match=true;
                    List<LabelValueBean> compare = CommonUtils.compareData(tmp,formal,PTxnGroup.class);
                    if(CollectionUtils.isNotEmpty(compare)){
                        updCompare.put(tmp.getTxnGroup(),formal);
                    }
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                addCompare.put(tmp.getTxnGroup(),tmp);
            }
        }
        for(PTxnGroup formal :formals){
            boolean match = false;

            label1:for(PTxnGroup tmp :tmps){
                if(tmp.getTxnGroup().equals(formal.getTxnGroup())){
                    match=true;
                    //跳出当前循环
                    break label1;
                }
            }
            if(!match){
                delCompare.put(formal.getTxnGroup(),formal);
            }
        }

        if(!addCompare.isEmpty()||!updCompare.isEmpty()||!delCompare.isEmpty()){
            return new CompareDataBean(addCompare,updCompare,delCompare);
        }else{
            return null;
        }
    }

    /**
     * 组装交易大类及交易大类下的交易数据
     * @param txnGroupList
     * @param mchntAuthCtrlList
     * @param map
     * @param instId
     * @param prodCode
     * @return
     */
    @Override
    public List<PTxnGroup> getTxnGroup(List<MchntAuthCtrlInfoBean> txnGroupList, List<MchntAuthCtrlInfoBean> mchntAuthCtrlList, Map<String, String> map, String instId, String prodCode) {
        List<PTxnGroup> txnGroups = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(txnGroupList)){
            txnGroupList.stream().forEach(mchntAuthCtl ->{
                PTxnGroup txnGroup = new PTxnGroup();

                txnGroup.setTxnGroup(mchntAuthCtl.getTxnGroup());
                txnGroup.setProdCode(mchntAuthCtl.getBaseProdCode());
                txnGroup.setTxnGroupName(map.get(txnGroup.getTxnGroup()));
                txnGroup.setInstId(prodCode);
                //根据分组下面交易数判断交易分组是否被选中
                long count = mchntAuthCtrlList.stream().filter(auth->auth.getTxnGroup().equals(mchntAuthCtl.getTxnGroup())
                        &&auth.getBaseProdCode().equals(mchntAuthCtl.getBaseProdCode())
                        &&auth.getSupportFlag().equals(IgasYesOrNoEnum.Yes.getType())).count();
                if(count>0L){
                    txnGroup.setIsChecked(BusinessContainer.YES);
                }else{
                    txnGroup.setIsChecked(BusinessContainer.NO);
                }
//                txnGroup.setpTxnAuthMaps();
                List<PTxnAuthMap> pTxnAuthList = Lists.newArrayList();
                mchntAuthCtrlList.stream().filter(auth->auth.getTxnGroup().equals(mchntAuthCtl.getTxnGroup())
                        &&auth.getBaseProdCode().equals(mchntAuthCtl.getBaseProdCode())
                        &&auth.getSupportFlag().equals(IgasYesOrNoEnum.Yes.getType())).forEach(auth->{
                    PTxnAuthMap p = new PTxnAuthMap();
                    BeanUtils.copyProperties(auth,p);
                    p.setProdCode(auth.getBaseProdCode());
                    p.setSupportAcctType(auth.getSupportFlag());
                    if(IgasYesOrNoEnum.Yes.getType().equals(auth.getSupportFlag())){
                        p.setIsChecked(BusinessContainer.YES);
                    }else{
                        p.setIsChecked(BusinessContainer.NO);
                    }
                    p.setInstId(instId);
                    pTxnAuthList.add(p);
                });
                txnGroup.setpTxnAuthMaps(pTxnAuthList);
                txnGroups.add(txnGroup);
            } );
        }
        return txnGroups;
    }


    /**
     * 组装基础产品交易大类及交易大类下的交易数据
     * @param txnGroupList
     * @param map
     * @param instId
     * @param prodCode
     * @return
     */
    @Override
    public List<PTxnGroup> getBProdAuthCtrlTxnGroup(List<ProdAuthCtrlBean> selectedTxnNums, List<ProdAuthCtrlBean> txnGroupList, Map<String, String> map, String instId, String prodCode) {
        List<PTxnGroup> txnGroups = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(txnGroupList)){
            txnGroupList.stream().forEach(mchntAuthCtl ->{
                PTxnGroup txnGroup = new PTxnGroup();

                txnGroup.setTxnGroup(mchntAuthCtl.getTxnGroup());
//                txnGroup.setProdCode(mchntAuthCtl.getBaseProdCode());
                txnGroup.setTxnGroupName(map.get(txnGroup.getTxnGroup()));

                //根据分组下面交易数判断交易分组是否被选中
                long count = selectedTxnNums.stream().filter(auth->auth.getTxnGroup().equals(mchntAuthCtl.getTxnGroup())
//                        &&auth.getBaseProdCode().equals(mchntAuthCtl.getBaseProdCode())
                        &&auth.getSupportFlag().equals(IgasYesOrNoEnum.Yes.getType())).count();

//                txnGroup.setpTxnAuthMaps();
                List<PTxnAuthMap> pTxnAuthList = Lists.newArrayList();
                selectedTxnNums.stream().filter(auth->auth.getTxnGroup().equals(mchntAuthCtl.getTxnGroup())
//                        &&auth.getBaseProdCode().equals(mchntAuthCtl.getBaseProdCode())
                        &&auth.getSupportFlag().equals(IgasYesOrNoEnum.Yes.getType())).forEach(auth->{
                    PTxnAuthMap p = new PTxnAuthMap();
                    BeanUtils.copyProperties(auth,p);
//                    p.setProdCode(auth.getBaseProdCode());
                    p.setSupportAcctType(auth.getSupportFlag());
                    p.setInstId(instId);
                    pTxnAuthList.add(p);
                });
                txnGroup.setpTxnAuthMaps(pTxnAuthList);
                txnGroups.add(txnGroup);
            } );
        }
        return txnGroups;
    }

    /**
     * 将标准产品信息对象转化成商户产品信息对象
     * @param prodInfoResp
     * @param mchntProdResp
     */
    @Override
    public void getMchntProdFromProd(ProdInfoQueryResponse prodInfoResp, MchntProdInfoQueryResponse mchntProdResp, String baseProdCode){

        BeanUtils.copyProperties(prodInfoResp,mchntProdResp);
        List<MchntStageInfoBean> mchntStageList = Lists.newArrayList();
        List<ProdStageInfoBean> prodStageList = prodInfoResp.getProdStageInfoList();
        if(CollectionUtils.isNotEmpty(prodStageList)){
            for (ProdStageInfoBean prodStage:prodStageList){
                if(Common.isNotBlank(prodStage)){
                    MchntStageInfoBean mchntStage = new MchntStageInfoBean();
                    BeanUtils.copyProperties(prodStage,mchntStage);
                    mchntStage.setMchntStageFee(prodStage.getProdStageFee());
                    mchntStage.setBaseProdCode(baseProdCode);
                    mchntStage.setMchntStageNum(Integer.parseInt(prodStage.getProdStageNum()));
                    mchntStageList.add(mchntStage);
                }
            }
        }
        List<MchntFeeInfoBean> mchntFeeList = Lists.newArrayList();
        List<ProdFeeInfoBean> prodFeeList = prodInfoResp.getProdFeeInfoList();
        if(CollectionUtils.isNotEmpty(prodFeeList)){
            for (ProdFeeInfoBean prodFee:prodFeeList){
                if(Common.isNotBlank(prodFee)){
                    MchntFeeInfoBean mchntFee = new MchntFeeInfoBean();
                    BeanUtils.copyProperties(prodFee,mchntFee);
                    mchntFee.setBaseProdCode(baseProdCode);
                    mchntFeeList.add(mchntFee);
                }
            }
        }
        List<MchntAuthCtrlInfoBean> mchntAuthCtrlList = Lists.newArrayList();
        List<ProdAuthCtrlBean> prodAuthCtrlList = prodInfoResp.getProdAuthCtrlList();
        if(CollectionUtils.isNotEmpty(prodAuthCtrlList)){
            for (ProdAuthCtrlBean prodAuthCtrl:prodAuthCtrlList){
                if(Common.isNotBlank(prodAuthCtrl)){
                    MchntAuthCtrlInfoBean mchntAuthCtrl = new MchntAuthCtrlInfoBean();
                    BeanUtils.copyProperties(prodAuthCtrl,mchntAuthCtrl);
                    mchntAuthCtrl.setBaseProdCode(baseProdCode);
                    mchntAuthCtrlList.add(mchntAuthCtrl);
                }
            }
        }
        mchntProdResp.setMchntStageInfoList(mchntStageList);
        mchntProdResp.setMchntFeeInfoList(mchntFeeList);
        mchntProdResp.setMchntAuthCtrlInfoList(mchntAuthCtrlList);
    }

    /**
     * 将标准产品信息对象转化成商户产品信息对象
     * @param prodInfoResp
     * @param mchntProdResp
     */
    @Override
    public void getMchntAuthCtrlFromProd(ProdInfoQueryResponse prodInfoResp, MchntProdInfoQueryResponse mchntProdResp){
        List<MchntAuthCtrlInfoBean> mchntAuthCtrlList = mchntProdResp.getMchntAuthCtrlInfoList();
        List<MchntAuthCtrlInfoBean> mchntAuthCtrlNoList = Lists.newArrayList();
        List<ProdAuthCtrlBean> prodAuthCtrlList = prodInfoResp.getProdAuthCtrlList();
        if(CollectionUtils.isNotEmpty(prodAuthCtrlList)&&CollectionUtils.isNotEmpty(mchntAuthCtrlList)){
            prodAuthCtrlList.stream().filter(prodAuthCtrl->
                    mchntAuthCtrlList.stream().noneMatch(mchntAuthCtrl ->
                            (mchntAuthCtrl.getBizType().equals(prodAuthCtrl.getBizType())
                                    &&mchntAuthCtrl.getTxnGroup().equals(prodAuthCtrl.getTxnGroup())
                                    &&mchntAuthCtrl.getTxnNum().equals(prodAuthCtrl.getTxnNum())) )).forEach(prodAuthCtrl->{
                MchntAuthCtrlInfoBean mchntAuthCtrl = new MchntAuthCtrlInfoBean();
                BeanUtils.copyProperties(prodAuthCtrl,mchntAuthCtrl);
                //商户无、标准产品有的交易权限暂设置为不支持，界面用来控制是否勾选
                mchntAuthCtrl.setSupportFlag(IgasYesOrNoEnum.No.getType());
                mchntAuthCtrlNoList.add(mchntAuthCtrl);
            });
        }
    }

    /**
     * 将 商户产品信息视图对象 转换成 商户产品信息管理请求对象
     * @param req
     * @param bProdInfo
     * @throws RedpException
     */
    @Override
    public void getMchntProdManageFromVO(MchntProdInfoManageRequest req, MchntProdManagerVO bProdInfo) throws RedpException{

        if(Common.isBlank(req)){
            req = new MchntProdInfoManageRequest();
        }
        BeanUtils.copyProperties(bProdInfo,req);
        if(Common.isNotBlank(bProdInfo.getMchntProdUnitedFee())){
            MchntFeeInfoBean mchntFeeInfoBean=new MchntFeeInfoBean();
            BeanUtils.copyProperties(bProdInfo.getMchntProdUnitedFee(),mchntFeeInfoBean);
            SimpleDateFormat fmtdt1 = new SimpleDateFormat("yyyyMMdd");
            String date = fmtdt1.format(new Date());
            mchntFeeInfoBean.setFeeEffectiveDate(date);
            mchntFeeInfoBean.setFeeExpiryDate(BusinessContainer.doomsday);
            req.setMchntFeeInfoBean(mchntFeeInfoBean);
        }
        List<BaseProdBean> baseProdBeanList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(bProdInfo.getMchntBaseProdList())){
            for(MchntBaseProdManagerVO base: bProdInfo.getMchntBaseProdList()){
                BaseProdBean bean = new BaseProdBean();
                bean.setBaseProdCode(base.getBaseProdCode());
                bean.setCupsChannelMchntNo(base.getCupsChannelMchntNo());
                bean.setMchntSignType(base.getMchntSignType());
                bean.setOprType(base.getOprType());
                if(CollectionUtils.isNotEmpty(base.getMchntAuthCtrlInfoList())){
                    bean.setMchntAuthCtrlInfoBeanList(base.getMchntAuthCtrlInfoList());
                }
                if(CollectionUtils.isNotEmpty(base.getMchntFeeInfoList())){
                    bean.setMchntFeeInfoBeanList(base.getMchntFeeInfoList());
                }
                if(CollectionUtils.isNotEmpty(base.getMchntStageInfoList())){
                    bean.setMchntStageInfoBeanList(base.getMchntStageInfoList());
                }
                baseProdBeanList.add(bean);
            }
            if(Common.isNotBlank(bProdInfo.getMchntBaseProdList().get(0).getWechatAppid())){
                baseProdBeanList.get(0).setWechatAppid(bProdInfo.getMchntBaseProdList().get(0).getWechatAppid());
            }
            if(Common.isNotBlank(bProdInfo.getMchntBaseProdList().get(0).getWechatAppidKey())){
                baseProdBeanList.get(0).setWechatAppidKey(bProdInfo.getMchntBaseProdList().get(0).getWechatAppidKey());
            }
            if(Common.isNotBlank(bProdInfo.getMchntBaseProdList().get(0).getWechatMiniAppid())){
                baseProdBeanList.get(0).setWechatMiniAppid(bProdInfo.getMchntBaseProdList().get(0).getWechatMiniAppid());
            }
            if(Common.isNotBlank(bProdInfo.getMchntBaseProdList().get(0).getWechatMiniAppidKey())){
                baseProdBeanList.get(0).setWechatMiniAppidKey(bProdInfo.getMchntBaseProdList().get(0).getWechatMiniAppidKey());
            }
            if(Common.isNotBlank(bProdInfo.getMchntBaseProdList().get(0).getWechatSelfEntryFlag())){
                baseProdBeanList.get(0).setWechatSelfEntryFlag(bProdInfo.getMchntBaseProdList().get(0).getWechatSelfEntryFlag());
            }

        }
        req.setBaseProdBeanList(baseProdBeanList);
    }
}
